package com.xing.algorithm.string;

public class LongestCommonPrefix {
    public static String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length == 0) {
            return "";
        }
        if(strs.length == 1) {
            return strs[0];
        }

        for(int i = 0; i < strs[0].length(); i ++) {

            for(int j = 1; j < strs.length; j ++) {
                if(i >= strs[j].length() || strs[0].charAt(i) != strs[j].charAt(i)){
                    return strs[0].substring(0, i);
                }
            }
        }


        return strs[0];
    }


    public static String longestCommonPrefix2(String[] strs) {
        if(strs == null || strs.length == 0) {
            return "";
        }
        String res = strs[0];
        for (String str : strs) {
            System.out.println(str.indexOf(res));
            while (str.indexOf(res) != 0) {

                res = res.substring(0, res.length() - 1);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        String[] strs = new String[]{
                "flower","flow","flight"
        };
        System.out.println(longestCommonPrefix2(strs));

    }
}
